﻿"use strict";

var carApp = {};

carApp.carDatabase = [];

carApp.Car = function (make, model) {
    this.make = make;
    this.model = model;
}

//Create
carApp.create = function () {
    var make = document.getElementById('make').value;
    var model = document.getElementById('model').value;

    var newCar = new this.Car(make, model);
    this.carDatabase.push(newCar);

    this.read();
}

//Read
carApp.read = function () {
    var car = {};
    var h = '<table>';
    h += '<tr><th>Make</th><th>Model</th><th>Operation</th></tr>';

    for (var i = 0; i < this.carDatabase.length; i++) {
        car = this.carDatabase[i];
        h += '<tr>';
        h += '<td><span id="makeLabel' + i + '">' + car.make + '</span>';
        h += '<input type="text" id="make' + i + '" value="' + car.make + '" style="display: none;" /></td>';
        
        h += '<td><span id="modelLabel' + i + '">' + car.model + '</span>';
        h += '<input type="text" id="model' + i + '" value="' + car.model + '" style="display: none;" /></td>';

        h += '<td><button id="e' + i + '" onclick="carApp.edit(' + i + ')">Edit</button>';
        h += '<button id="d' + i + '" onclick="carApp.delete(' + i + ')">Delete</button>';
        h += '<button id="s' + i + '" onclick="carApp.save(' + i + ')" style="display: none;">Save</button></td>';
        h += '</tr>';
    }

    h += '</table>';
    document.getElementById('output').innerHTML = h;
}

carApp.edit = function (i) {
    var car = this.carDatabase[i];

    var makeLabel = document.getElementById('makeLabel' + i);
    var modelLabel = document.getElementById('modelLabel' + i);
    var make = document.getElementById('make' + i);
    var model = document.getElementById('model' + i);

    var editButton = document.getElementById('e' + i);
    var saveButton = document.getElementById('s' + i);

    //Hide the labels and the edit button
    makeLabel.style.display = 'none';
    modelLabel.style.display = 'none';
    editButton.style.display = 'none';

    //Show the inputs and the save button
    make.style.display = '';
    model.style.display = '';
    saveButton.style.display = '';
}

carApp.save = function (i) {
    var car = this.carDatabase[i];

    var make = document.getElementById('make' + i);
    var model = document.getElementById('model' + i);

    car.make = make.value;
    car.model = model.value;

    this.read();
}

carApp.delete = function (i) {
    this.carDatabase.splice(i, 1);

    this.read();
}